/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author luhonghai
 */
public class StudentManager {
    
    public List<Student> listAll() {
        List<Student> students = new ArrayList<Student>();
        
        Connection conn = DBConnector.getConnection();
        try {
            PreparedStatement stmt = conn.prepareStatement("SELECT [id] ,[name] ,[description] FROM [Student]");
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                Student std = new Student();
                std.setId(rs.getInt("id"));
                std.setName(rs.getString("name"));
                std.setDescription(rs.getString("description"));
                students.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentManager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        return students;
    }
    
    public void updateStudent(Student std) {
        Connection conn = DBConnector.getConnection();
        try {
            PreparedStatement stmt = conn.prepareStatement("UPDATE [Student]  SET [id] = ?,[name] = ?,[description] = ? WHERE ID=?");
            stmt.setInt(1, std.getId());
            stmt.setString(2, std.getName());
            stmt.setString(3, std.getDescription());
            stmt.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentManager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
}
